import FileSaver from 'file-saver'
import XLSX from 'xlsx'

/**
 * 生成从minNum到maxNum的随机数
 * 如果指定decimalNum个数，则生成指定小数位数的随机数
 * 如果不指定任何参数，则生成0-1之间的随机数
 * @param {*} maxNum 数据类型是Integer]生成的随机数的最小值（minNum和maxNum可以调换位置）
 * @param {*} minNum 数据类型是Integer]生成的随机数的最大值
 * @param {*} decimalNum 数据类型是Integer]如果生成的是带有小数的随机数，则指定随机数的小数点后的位数
 */
export default {
  randomNum(maxNum, minNum, decimalNum) {
    var max = 0,
      min = 0
    minNum <= maxNum
      ? ((min = minNum), (max = maxNum))
      : ((min = maxNum), (max = minNum))
    switch (arguments.length) {
      case 1:
        return Math.floor(Math.random() * (max + 1))
      case 2:
        return Math.floor(Math.random() * (max - min + 1) + min)
      case 3:
        return (Math.random() * (max - min) + min).toFixed(decimalNum)
      default:
        return Math.random()
    }
  },

  toTableData(data) {
    let tableData = {}
    let arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
    tableData.col = data[0].map((item, index) => {
      return {
        prop: `col${arr[index]}`,
        label: item
      }
    })

    tableData.row = data.splice(1, data.length).map(item => {
      let row = {}
      item.forEach((item, index) => {
        row[`col${arr[index]}`] = item
      })
      return row
    })

    return tableData
  },

  exportExcel(id, name) {
    /* out-table关联导出的dom节点  */
    var wb = XLSX.utils.table_to_book(document.querySelector(id))
    /* get binary string as output */
    var wbout = XLSX.write(wb, {
      bookType: 'xlsx',
      bookSST: true,
      type: 'array'
    })
    try {
      FileSaver.saveAs(
        new Blob([wbout], { type: 'application/octet-stream' }),
        `${name}.xlsx`
      )
    } catch (e) {
      if (typeof console !== 'undefined') console.log(e, wbout)
    }
    return wbout
  }
}
